package concurrent;

import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Created by chenxin34 on 2020/3/9 下午7:02.
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(0);
        new Thread(() -> {
            System.out.println("#1");
            try {
                boolean a = semaphore.tryAcquire(1, 10, TimeUnit.SECONDS);
                System.out.println(new Date() + "#2-1" + a);
                semaphore.drainPermits();
                boolean b = semaphore.tryAcquire(1, 10, TimeUnit.SECONDS);
                System.out.println(new Date() + " #2-2" + b);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("#3");
            try {
                semaphore.release(2);
                System.out.println("#4");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
